package com.ufo.store.management.ui.fragment;

import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.Member;
import com.ufo.store.management.utils.AnimationUtil;
import com.ufo.store.management.widget.view.FloatTextToast;
import com.ufo.store.management.widget.dialog.ProtogenesisInputDialog;
import com.ufo.store.management.widget.dialog.TipsDialog;

import java.text.SimpleDateFormat;

/**
 *  作者：taoli on 2017/9/12 0012 09:15
 *  
 */
public class MemberEditFragment extends Fragment{
    private LinearLayout mRootLayout = null;
    private EditText mMemberIdEt = null;
    private EditText mMemberNameEt = null;
    private EditText mMemberSexEt = null;
    private EditText mMemberMobileEt = null;
    private EditText mMemberTypeEt = null;
    private EditText mMemberCardidEt = null;
    private EditText mMemberPointEt = null;
    private EditText mMemberTotalConsumeEt = null;

    private TipsDialog mTipsDialog = null;

    private Member mMemberInfo = null;
    private boolean mbIsInsertData = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootLayout = (LinearLayout) inflater.inflate(R.layout.fragment_member_edit, container, false);
        mbIsInsertData = getArguments().getBoolean("IsInsertData");
        mMemberInfo = (Member) getArguments().getSerializable("MemberInfo");
        LinearLayout content_ll = (LinearLayout)mRootLayout.findViewById(R.id.content_ll);
        AnimationUtil.setTopToBottomAnimation(content_ll,350,0.1f);
        initialize(mRootLayout);
        initData();
        return mRootLayout;
    }

    private void initialize(View rootView){
        mMemberIdEt = (EditText) rootView.findViewById(R.id.member_id_et);
        mMemberNameEt = (EditText) rootView.findViewById(R.id.member_name_et);
        mMemberSexEt = (EditText) rootView.findViewById(R.id.member_sex_et);
        mMemberMobileEt = (EditText) rootView.findViewById(R.id.member_mobile_et);
        mMemberTypeEt = (EditText) rootView.findViewById(R.id.member_type_et);
        mMemberCardidEt = (EditText) rootView.findViewById(R.id.member_cardid_et);
        mMemberPointEt = (EditText) rootView.findViewById(R.id.member_point_et);
        mMemberTotalConsumeEt = (EditText) rootView.findViewById(R.id.member_totalconsume_et);

        mMemberIdEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mMemberCardidEt.setText(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        if (mMemberInfo != null) {
            mMemberIdEt.setText(mMemberInfo.memberId);
            mMemberNameEt.setText(mMemberInfo.memberName);
            mMemberSexEt.setText(mMemberInfo.memberSex);
            mMemberMobileEt.setText(mMemberInfo.memberMobile);
            mMemberTypeEt.setText(mMemberInfo.memberType);
            mMemberPointEt.setText(String.valueOf(mMemberInfo.memberPoint));
            mMemberTotalConsumeEt.setText(String.valueOf(mMemberInfo.memberTotalConsume) + "元");
        }
    }

    private void initData(){

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl1:
            case R.id.member_id_et:
                new ProtogenesisInputDialog(getActivity(), mMemberIdEt, "会员序号、卡号", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mMemberIdEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl2:
            case R.id.member_name_et:
                new ProtogenesisInputDialog(getActivity(), mMemberNameEt, "会员姓名", null).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mMemberNameEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl3:
            case R.id.member_sex_et:
                pickSex();
                break;
            case R.id.rl4:
            case R.id.member_mobile_et:
                new ProtogenesisInputDialog(getActivity(), mMemberMobileEt, "电话", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mMemberMobileEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl5:
            case R.id.member_type_et:
                pickCard();
                break;
            case R.id.rl6:
            case R.id.member_cardid_et:
                new ProtogenesisInputDialog(getActivity(), mMemberCardidEt, "会员卡卡号", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mMemberCardidEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl7:
            case R.id.member_point_et:

                break;
            case R.id.rl8:
            case R.id.member_totalconsume_et:

                break;
        }
    }

    public void submitMemberEdit() {
        String memberIdEtStr = mMemberIdEt.getText().toString();
        String memberNameEtStr = mMemberNameEt.getText().toString();
        String memberSexEtStr = mMemberSexEt.getText().toString();
        String memberMobileEtStr = mMemberMobileEt.getText().toString();
        String memberTypeEtStr = mMemberTypeEt.getText().toString();
        String memberCardidEtStr = mMemberCardidEt.getText().toString();

        if (memberIdEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mMemberIdEt, "会员ID不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (memberMobileEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mMemberMobileEt, "会员电话不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (memberTypeEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mMemberTypeEt, "会员卡类型不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (memberCardidEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mMemberCardidEt, "会员卡ID不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String memberBirthdayStr = format.format(mMemberInfo.memberBirthday);
        String memberCreateDateStr = format.format(mMemberInfo.memberCreateDate);

        try {
            ContentValues initialValues = new ContentValues();
            initialValues.put(DatabaseManager.MEMBER_MEMBERID, memberIdEtStr);
            initialValues.put(DatabaseManager.MEMBER_NAME, memberNameEtStr);
            initialValues.put(DatabaseManager.MEMBER_SEX, memberSexEtStr);
            initialValues.put(DatabaseManager.MEMBER_TELEPHONE, memberMobileEtStr);
            initialValues.put(DatabaseManager.MEMBER_MOBILE, memberMobileEtStr);
            initialValues.put(DatabaseManager.MEMBER_POST, new String());
            initialValues.put(DatabaseManager.MEMBER_ADDR, new String());
            initialValues.put(DatabaseManager.MEMBER_EMAIL, new String());
            initialValues.put(DatabaseManager.MEMBER_MEMO, new String());
            initialValues.put(DatabaseManager.MEMBER_BIRTHDAY, memberBirthdayStr);
            initialValues.put(DatabaseManager.MEMBER_CREATE_DATE, memberCreateDateStr);
            initialValues.put(DatabaseManager.MEMBER_CREATE_OPERID, new String());
            initialValues.put(DatabaseManager.MEMBER_STATE, "有效");
            initialValues.put(DatabaseManager.MEMBER_AMOUNT, 0);
            initialValues.put(DatabaseManager.MEMBER_OVERDRAFT, "N");
            initialValues.put(DatabaseManager.MEMBER_PASSWORD, new String());
            initialValues.put(DatabaseManager.MEMBER_DISCOUNTE, 1);
            initialValues.put(DatabaseManager.MEMBER_POINT, 0);
            initialValues.put(DatabaseManager.MEMBER_POINT_FLAG, "Y");
            initialValues.put(DatabaseManager.MEMBER_PRICE_KIND, "LSJ");
            initialValues.put(DatabaseManager.MEMBER_MEMBERTYPE, memberTypeEtStr);
            initialValues.put(DatabaseManager.MEMBER_CARDID, memberCardidEtStr);
            initialValues.put(DatabaseManager.MEMBER_CARD_MEDIUM, 0);
            initialValues.put(DatabaseManager.MEMBER_MODIFY_SN, mMemberInfo.memberModifySn);
            initialValues.put(DatabaseManager.MEMBER_CARD_RECHARGE, 0);
            initialValues.put(DatabaseManager.MEMBER_CARD_PRESENT, 0);
            initialValues.put(DatabaseManager.MEMBER_CARD_CONSUME, 0);
            initialValues.put(DatabaseManager.MEMBER_TOTAL_CONSUME, 0);
            initialValues.put(DatabaseManager.MEMBER_CREATE_SHOPID, new String());
            initialValues.put(DatabaseManager.MEMBER_EXPIRE_DATE, new String());

            new SubmitMemberInfoTask().execute(initialValues);

        } catch (Exception e) {
            return;
        }
    }

    private class SubmitMemberInfoTask extends AsyncTask<ContentValues, Void, String> {
        public SubmitMemberInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(ContentValues... params) {
            if (getActivity().isFinishing()) {
                return "";
            }
            final ContentValues initialValues = params[0];
            long row = -1;
            if( BarApplication.getInstance().mDatabaseIsSqlServer) {
                if (mbIsInsertData)
                    row = DatabaseManager.insertMemberInfoFromSqlServer(getActivity(), initialValues);
                else
                    row = DatabaseManager.replaceMemberInfoFromSqlServer(getActivity(), initialValues);
            }
            return String.valueOf(row);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (getActivity().isFinishing()) {
                return;
            }
            if (result.contains("-1")) {
                if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                    showTipsDialog("对不起，信息修改失败。");
                } else if(mOnProcessListener!=null){
                    mOnProcessListener.onProcessFinish(mMemberIdEt.getText().toString());
                }
            }else {
                if(mOnProcessListener!=null){
                    mOnProcessListener.onProcessFinish(mMemberIdEt.getText().toString());
                }
                getActivity().setResult(Activity.RESULT_OK);
                showTipsDialog("恭喜，成功修改了" + result + "条数据。");
            }
        }
    }

    public void showTipsDialog(final String tips) {
        if (mTipsDialog == null) {
            mTipsDialog = new TipsDialog(getActivity());
            Window window = mTipsDialog.getWindow(); //得到对话框
            window.setWindowAnimations(R.style.dialog_anim_center_style); //设置窗口弹出动画
        }
        mTipsDialog.setTips(tips);
        mTipsDialog.setItemClickListener(new TipsDialog.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                if (position == 0) {
                }
            }
        });
        mTipsDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        mTipsDialog.show();
    }

    private void pickSex() {
        final String[] items = new String[] { "男", "女" };
        int index = 1;
        if(mMemberSexEt.getText().toString().equals("男")) {
            index = 0;
        }
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("性别")
                .setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            mMemberSexEt.setText("男");
                        } else if (which == 1) {
                            mMemberSexEt.setText("女");
                        }
                        dialog.dismiss();
                    }
                }).create();
        alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
        alertDialog.show();
    }

    private void pickCard() {
        final String[] items = new String[] { "普通卡", "VIP金卡" };
        int index = 1;
        if(mMemberTypeEt.getText().toString().equals("普通卡")) {
            index = 0;
        }
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("会员卡类型")
                .setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            mMemberTypeEt.setText("普通卡");
                        } else if (which == 1) {
                            mMemberTypeEt.setText("VIP金卡");
                        }
                        dialog.dismiss();
                    }
                }).create();
        alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
        alertDialog.show();
    }

    private OnProcessListener mOnProcessListener = null;

    public void setOnProcessListener(OnProcessListener l) {
        mOnProcessListener = l;
    }

    public interface OnProcessListener {
        public void onProcessFinish(String memberId);
    }
}
